var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var _this = this;
var mainContent = document.getElementsByClassName('mainContent')[0]; //主题内容部分
var navRadio = document.getElementsByClassName('radio')[0]; //获取单选框导航层
var inputContent = document.getElementsByClassName('inputContent')[0]; // input输入框
var inputModify = document.createElement('input'); //修改时的input输入框
var radioAll = document.getElementsByClassName('all')[0]; // '所有' 的单选框
var status1 = 'all'; // 默认为all，导航栏的
// 封装fetch
var fetchData = function (url, method, data) { return __awaiter(_this, void 0, void 0, function () {
    var response, err_1, response, err_2;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                if (!(method.toUpperCase() === 'GET')) return [3 /*break*/, 5];
                _a.label = 1;
            case 1:
                _a.trys.push([1, 4, , 5]);
                return [4 /*yield*/, fetch(url)];
            case 2:
                response = _a.sent();
                return [4 /*yield*/, response.json()];
            case 3: return [2 /*return*/, _a.sent()];
            case 4:
                err_1 = _a.sent();
                throw new Error(err_1);
            case 5:
                if (!(method.toUpperCase() === 'POST')) return [3 /*break*/, 10];
                _a.label = 6;
            case 6:
                _a.trys.push([6, 9, , 10]);
                return [4 /*yield*/, fetch(url, {
                        method: method,
                        headers: {
                            'content-type': 'application/json; charset=utf-8'
                        },
                        body: data
                    })];
            case 7:
                response = _a.sent();
                return [4 /*yield*/, response.json()];
            case 8: return [2 /*return*/, _a.sent()];
            case 9:
                err_2 = _a.sent();
                throw new Error(err_2);
            case 10: return [2 /*return*/];
        }
    });
}); };
// 防抖
var debounce = function (fn, wait) {
    var timer = null;
    return function (e) {
        if (timer)
            clearTimeout(timer);
        timer = setTimeout(function () {
            fn(e);
        }, wait);
    };
};
// 节流
var throttle = function (fn, wait) {
    var canRun = true;
    return function (e, id) {
        if (!canRun)
            return;
        canRun = false;
        setTimeout(function () {
            fn(e, id);
            canRun = true;
        }, wait);
    };
};
// 创建主体部分节点
var createDOM = function (list) {
    var information;
    var moreInformation = '';
    list.forEach(function (item, i) {
        information = "<div class=\"information\">\n                            <div class=\"boxLabel\"><input type=\"checkbox\" name=\"hobby\" ".concat(item.state === 1 ? "checked" : "", " onclick=\"modifyStatus(").concat(item.id, ")\"><span>").concat(item.content, "</span></div>\n                            <p>\n                                <button class=\"modify\" onclick=\"modify(event, ").concat(item.id, ")\">\u4FEE\u6539</button>\n                                <button class=\"del\" onclick=\"del(").concat(item.id, ")\">\u5220\u9664</button>\n                            </p>\n                        </div>");
        moreInformation = moreInformation.concat(information);
    });
    mainContent.innerHTML = moreInformation;
};
// 修改选中状态
var modifyStatus = throttle(function (e, id) {
    fetchData('/todo/change', 'post', JSON.stringify({ id: id, nowState: status1 })).then(function (res) {
        createDOM(res.data);
    });
}, 1000);
// 删除元素
var del = throttle(function (e, id) {
    fetchData('/todo/del', 'post', JSON.stringify({
        id: id,
        nowState: status1
    })).then(function (res) {
        createDOM(res.data);
    });
}, 1000);
// 修改接口请求
var modifyData = function (id, newContent) {
    fetchData('/todo/edit', 'post', JSON.stringify({
        nowState: status1,
        newContent: newContent,
        id: id
    })).then(function (res) {
        createDOM(res.data);
    });
};
// 修改元素
var modify = throttle(function (e, id) {
    var boxLabel = e.target.parentNode.previousSibling.previousSibling;
    for (var i = 0; i < boxLabel.childNodes.length; i++) {
        if (boxLabel.childNodes[i].nodeName === 'SPAN') {
            inputModify.value = boxLabel.childNodes[i].innerHTML;
            boxLabel.removeChild(boxLabel.childNodes[i]);
        }
    }
    if (boxLabel.childNodes.length === 1) { //当div下只有一个多选框时才将text框加进去，不然会出现多次添加input的问题
        boxLabel.appendChild(inputModify);
    }
    inputModify.onblur = inputBlur({ targetEle: boxLabel, childEle: inputModify, id: id });
}, 1000);
// 修改输入框失去焦点事件
var inputBlur = function (_a) {
    var params = __rest(_a, []);
    return function (e) {
        params.targetEle.removeChild(params.childEle);
        modifyData(params.id, e.target.value);
    };
};
// 输入内容加到主体内容里
var addToMain = function (e) {
    var value = e.target.value;
    // 当输入框里有值的时候在请求接口
    if (value) {
        fetchData('/todo/add', 'post', JSON.stringify({
            content: value
        })).then(function (res) {
            createDOM(res.data);
        });
    }
    e.target.value = '';
    radioAll.checked = true;
};
// 点击切换单选框的选中状态
var clickRadio = function (e) {
    if (e.target.nodeName === 'INPUT') {
        status1 = e.target.value;
    }
    fetchData('/todo/getList?finishState=' + status1, 'get').then(function (res) {
        createDOM(res.data);
    });
};
// 页面刚进入时调用获取数据接口，渲染页面
var loadPage = function () {
    fetchData('/todo/getList?finishState=all', 'get').then(function (res) {
        createDOM(res.data);
    });
};
loadPage();
// 输入框失去焦点时将内容加到主体里
inputContent.onblur = debounce(addToMain, 1000);
// Enter键按下事件
inputContent.onkeydown = debounce(function (e) {
    if (e.keyCode === 13) { // enter对应13
        addToMain(e);
    }
}, 1000);
// 点击上方导航栏触发的页切事件
navRadio.onclick = debounce(clickRadio, 1000);
